from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect
from django.contrib.auth.hashers import check_password
from django.contrib.auth.hashers import make_password
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from . import models
from django.db.models import F
from django.db import connection
import base64
import json
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth import logout
import random
import string
from django.core.cache import cache
from PIL import Image, ImageDraw, ImageFont
from io import BytesIO
from django.utils.crypto import get_random_string

def logout_view(request):
    print('logout sucessful!')
    logout(request)  # 清除 Django 的 Auth session
    request.session.flush()  # 清除自定义的 session 数据
    return render(request, 'login_in.html')


# 简单的返回页面的视图函数
def index(request):
    return render(request, 'index.html')


def login(request):
    return render(request, 'login_in.html')


def sign_in(request):
    return render(request, 'sign_in.html')


def index_sign(request):
    # 将主页的登录重定向为注册页面
    return redirect('sign_in')


def index_login(request):
    return redirect('login')


def captcha_image(request):
    # 确保 session_key 非空
    if request.session.session_key is None:
        request.session.create()  # 创建 session

    # 生成4位随机验证码字符串
    captcha_str = ''.join(random.choices(string.ascii_letters + string.digits, k=4))

    # 将验证码字符串存储至缓存
    cache.set(f"{request.session.session_key}_captcha", captcha_str, timeout=300)  # 5分钟有效期

    # 创建随机背景颜色
    background_color = (
        random.randint(200, 255),
        random.randint(200, 255),
        random.randint(200, 255)
    )

    # 创建验证码图片
    image = Image.new('RGB', (120, 40), color=background_color)
    draw = ImageDraw.Draw(image)

    # 默认字体
    font_size = 25  # 设置字体大小
    try:
        font = ImageFont.truetype("arial.ttf", font_size)
    except IOError:
        font = ImageFont.load_default()  # 加载默认字体作为后备

    # 在随机位置绘制文本，添加旋转角度
    for i in range(len(captcha_str)):
        angle = random.randint(-30, 30)  # 随机旋转角度
        text_x = 10 + i * 25 + random.randint(-5, 5)  # 随机文本位置
        text_y = random.randint(5, 15)  # 随机文本高度
        draw.text((text_x, text_y), captcha_str[i], fill=(0, 0, 0), font=font)

    # 添加干扰线
    for _ in range(random.randint(5, 10)):  # 随机数量的干扰线
        start_x = random.randint(0, 120)
        start_y = random.randint(0, 40)
        end_x = random.randint(0, 120)
        end_y = random.randint(0, 40)
        draw.line((start_x, start_y, end_x, end_y), fill=(
            random.randint(0, 255),
            random.randint(0, 255),
            random.randint(0, 255)
        ), width=random.randint(1, 2))

    # 生成响应
    response = HttpResponse(content_type="image/png")
    buffer = BytesIO()
    image.save(buffer, format='PNG')
    response.write(buffer.getvalue())
    return response

def upload_signin_info(request):
    if request.method == 'POST':
        # 处理 POST 请求，获取到前端提交的username以及password
        username = request.POST.get('email')
        password = request.POST.get('password')
        identity = request.POST.get('identity')
        real_name = request.POST.get('real_name')
        captcha_input = request.POST.get('captchaInput')
        print(captcha_input)

        # 验证验证码
        valid_captcha = cache.get(request.session.session_key + '_captcha')
        if captcha_input.lower() != valid_captcha.lower():  # 修改这里
            return render(request, 'sign_in.html', {'error_message': '验证码错误'})
        print(identity)
        # 检查用户名或密码是否为空
        if not username or not password:
            return render(request, 'sign_in.html', {'error_message': '用户名和密码不能为空'})
        # 检查密码强度是否符合
        if len(password) < 8 or not any(char.isdigit() for char in password) or not any(char.isalpha() for char in password):
            return render(request, 'sign_in.html', {'error_message': '密码长度至少8位,且包含数字和字母!'})
        # 检查用户名是否已经存在
        if models.log.objects.filter(username=username).exists():
            return render(request, 'sign_in.html', {'error_message': '该用户名已经被注册'})
        # 对密码进行哈希处理
        pwd_after_hash = make_password(password)
        # 将内容写入数据库
        models.log.objects.create(username=username, password=pwd_after_hash, userrole=identity, realname=real_name)
        return render(request, 'login_in.html', {'success_message': '注册成功,请登录'})


def login_info(request):
    if request.method == 'POST':
        username = request.POST.get('email')
        request.session['email'] = username
        password = request.POST.get('password')
        print(f"用户名: {username}, 密码: {password}")  # 调试信息
        users = models.log.objects.filter(username=username)
        print(f"查询结果: {users}")  # 调试信息
        if users.exists():
            user = users.first()
            print(f"匹配到的用户: {user}")  # 调试信息
            if check_password(password, user.password):
                print(user.userrole)
                if user.userrole == '考生':
                    # 考生主页
                    return redirect('stu_index')
                elif user.userrole == '8':
                    # 复试组管理员
                    return redirect('registration_info')
                elif user.userrole == '2':
                    # 导师页面
                    return redirect('teacher_index')
                elif user.userrole == '5':
                    return redirect('Head_of_Discipline')
                elif user.userrole == '3':
                    return redirect('Subject_Secretary')
                elif user.userrole == '4':
                    return redirect('Graduate_supervisor_Secretary')
                elif user.userrole == '7':
                    return redirect('Graduate_supervisor_leadership')
                elif user.userrole == '6':
                    return redirect('admin')
            else:
                return render(request, 'login_in.html', {'error_message': '用户名或密码错误'})
        else:
            return render(request, 'login_in.html', {'error_message': '用户名或密码错误'})


# @login_required
def forgot_password(request):
    return render(request, 'forget_pwd.html')

from django.contrib.auth.hashers import make_password

def validate_password_reset_info(email, real_name, idnumber, new_pwd, conf_pwd):
    """
    验证用户身份信息和密码强度
    """
    # 检查邮箱和实名信息是否匹配
    student = models.student_table.objects.filter(email=email).first()
    if not (student and student.idnumber == idnumber and student.name == real_name):
        return '邮箱或实名信息填写错误！'

    # 检查新密码和确认密码是否一致
    if new_pwd != conf_pwd:
        return '新密码和确认密码不一致!'

    # 检查密码强度
    if len(new_pwd) < 8 or not any(char.isdigit() for char in new_pwd) or not any(char.isalpha() for char in new_pwd):
        return '密码长度至少8位,且包含数字和字母!'

    return None

def update_password(email, new_pwd):
    """
    更新用户密码
    """
    loginfo = models.log.objects.filter(username=email).first()
    loginfo.password = make_password(new_pwd)
    loginfo.save()
    return '密码重置成功,请重新登录!'

def reset_pwd(request):
    if request.method == 'POST':
        email = request.POST.get('email')
        real_name = request.POST.get('fullname')
        idnumber = request.POST.get('id_number')
        new_pwd = request.POST.get('newpwd')
        conf_pwd = request.POST.get('confpwd')

        # 验证用户信息和密码强度
        error_msg = validate_password_reset_info(email, real_name, idnumber, new_pwd, conf_pwd)
        if error_msg:
            return render(request, 'forget_pwd.html', {
                'email': email,
                'fullname': real_name,
                'id_number': idnumber,
                'new_password': new_pwd,
                'confirm_password': conf_pwd,
                'error_msg': error_msg
            })

        # 更新密码
        success_msg = update_password(email, new_pwd)
        return render(request, 'forget_pwd.html', {
            'success_msg': success_msg
        })
    else:
        # 初始化表单数据
        return render(request, 'forget_pwd.html', {
            'email': '',
            'fullname': '',
            'id_number': '',
            'new_password': '',
            'confirm_password': ''
        })

# 用来处理复试登记表中的学生信息
def input_stu_info(request):
    if request.method == 'POST':
        # 提取表单数据
        name = request.POST.get('name')
        stu_no = request.POST.get('stu_no')
        gender = request.POST.get('gender')
        major = request.POST.get('major')
        graduation_school = request.POST.get('graduation_school')
        graduation_time = request.POST.get('graduation_time')
        graduation_major = request.POST.get('graduation_major')
        stu_type = request.POST.get('stu_type')
        category = request.POST.get('category')
        contact_phone = request.POST.get('contact_phone')
        emergency_contact_phone = request.POST.get('emergency_contact_phone')
        preferred_mentor_1 = request.POST.get('preferred_mentor_1')
        preferred_mentor_2 = request.POST.get('preferred_mentor_2')
        preferred_mentor_3 = request.POST.get('preferred_mentor_3')
        research_direction = request.POST.get('research_direction')
        accept_adjustment = request.POST.get('accept_adjustment')
        adjustment_order_1 = request.POST.get('adjustment_order_1')
        adjustment_order_2 = request.POST.get('adjustment_order_2')
        adjustment_order_3 = request.POST.get('adjustment_order_3')
        adjustment_order_4 = request.POST.get('adjustment_order_4')

        # 获取学科ID
        subject_id_instance = models.subject_table.objects.filter(subjectname=major).first()
        subject_id = subject_id_instance.subjectid
        if subject_id is None:
            return JsonResponse({'error_message': '未找到专业对应的学科ID'}, status=400)

        # 进行特定逻辑的检查
        if subject_id == '081200':
            if research_direction is None and (
                    accept_adjustment or adjustment_order_1 or adjustment_order_2 or adjustment_order_3 or adjustment_order_4):
                return JsonResponse({'error_message': '请正确填写信息'}, status=400)
        elif subject_id == '085400':
            if research_direction and not (
                    accept_adjustment == None and adjustment_order_1 == None and adjustment_order_2 == None and adjustment_order_3 == None and adjustment_order_4 == None):
                return JsonResponse({'error_message': '请正确填写信息'}, status=400)
        else:
            return JsonResponse({'error_message': '请正确填写复试学科专业'}, status=400)

        # 然后检查是否已经存在该学生的记录
        existing_info = models.registration_table.objects.filter(examnumber__exam_number_field=stu_no).first()

        # 获取或创建 SubjectId 实例
        subject_instance, created = models.SubjectId.objects.get_or_create(subject_id_field=subject_id)

        if existing_info:
            # 如果存在，更新记录
            existing_info.name = name
            existing_info.gender = gender
            existing_info.undergradmajor = graduation_major
            existing_info.undergradschool = graduation_school
            existing_info.graduationtime = graduation_time
            existing_info.subjectid = subject_instance  # 使用 SubjectId 实例
            existing_info.subjectname = major
            existing_info.stu_type = stu_type
            existing_info.category = category
            existing_info.phone = contact_phone
            existing_info.emergencyphone = emergency_contact_phone
            existing_info.preferred_mentor_1 = preferred_mentor_1
            existing_info.preferred_mentor_2 = preferred_mentor_2
            existing_info.preferred_mentor_3 = preferred_mentor_3
            existing_info.research_direction = research_direction
            existing_info.accept_adjustment = accept_adjustment
            existing_info.adjustment_order_1 = adjustment_order_1
            existing_info.adjustment_order_2 = adjustment_order_2
            existing_info.adjustment_order_3 = adjustment_order_3
            existing_info.adjustment_order_4 = adjustment_order_4

            existing_info.save()  # 保存更新后的记录
        else:
            # 如果不存在，则创建新记录
            ExamNumber_instance, created = models.ExamNumber.objects.get_or_create(exam_number_field=stu_no)
            Information = models.registration_table(
                name=name,
                examnumber=ExamNumber_instance,
                gender=gender,
                undergradmajor=graduation_major,
                undergradschool=graduation_school,
                graduationtime=graduation_time,
                subjectid=subject_instance,  # 使用 SubjectId 实例
                subjectname=major,
                stu_type=stu_type,
                category=category,
                phone=contact_phone,
                emergencyphone=emergency_contact_phone,
                preferred_mentor_1=preferred_mentor_1,
                preferred_mentor_2=preferred_mentor_2,
                preferred_mentor_3=preferred_mentor_3,
                research_direction=research_direction,
                accept_adjustment=accept_adjustment,
                adjustment_order_1=adjustment_order_1,
                adjustment_order_2=adjustment_order_2,
                adjustment_order_3=adjustment_order_3,
                adjustment_order_4=adjustment_order_4
            )
            Information.save()  # 保存新记录
        ExamNumber_instance, created = models.ExamNumber.objects.get_or_create(exam_number_field=stu_no)
        stu_tch = models.student_teacher.objects.filter(examnumber=ExamNumber_instance).first()
        teacher = models.teacher_table.objects.filter(instructorname=preferred_mentor_1).first()
        print(teacher.instructorid)
        teacher_instance, created = models.TeacherId.objects.get_or_create(teacher_id_field=teacher.instructorid)
        stu_tch.instructorid = teacher_instance
        stu_tch.current_wish = '1'
        stu_tch.status = '0'
        stu_tch.save()

        return JsonResponse({'success_message': '提交成功！'})


def registration_info(request):
    students = models.firstscore_table.objects.all()
    student_infos = []

    for stu in students:
        # 假设 examnumber 是一个外键，那么应该使用 examnumber_id 来获取关联对象的ID
        stu_examnumber_id = stu.examnumber_id  # 获取关联学生表的ID
        stu_byid = models.student_table.objects.filter(examnumber=stu_examnumber_id).first()
        if stu_byid:
            student_info = {
                'examnumber': stu_examnumber_id,
                'name': stu_byid.name,
                'mathscore': stu.mathscore,
                'englishscore': stu.englishscore,
                'majorscore': stu.majorscore,
                'politicalscore': stu.politicalscore,
            }
            student_infos.append(student_info)
        else:
            print("No matching student found")
    # 分页处理
    paginator = Paginator(student_infos, 8)
    page = request.GET.get('page')
    try:
        student_infos = paginator.page(page)
    except PageNotAnInteger:
        student_infos = paginator.page(1)
    except EmptyPage:
        student_infos = paginator.page(paginator.num_pages)
    # 将 student_infos 传递给模板进行渲染
    return render(request, '复试组后台.html', {'student_infos': student_infos})


# 开始复试函数、还需编写获取数据的视图函数，从复试信息表中根据前前面获取到的stu_id来找到相关信息
def start_registration(request):
    if request.method == 'POST':
        stu_no = request.POST.get('stu_id')
        stu = models.registration_table.objects.filter(examnumber=stu_no).first()
        stu.state = '1'
        if stu.gender:
            if stu.gender == '1':
                stu.gender = '男'
            else:
                stu.gender = '女'
        if stu.stu_type:
            if stu.stu_type == '1':
                stu.stu_type = '应届生'
            elif stu.stu_type == '2':
                stu.stu_type = '往届生'
            else:
                stu.stu_type = '同等学力'
        if stu.category:
            if stu.category == '1':
                stu.category = '定向生'
            else:
                stu.category = '非定向考生'
        if stu.subjectname == '计算机科学与技术':
            research_direction = stu.research_direction
            accept_adjustment = ''
            adjustment_order_1 = ''
            adjustment_order_2 = ''
            adjustment_order_3 = ''
            adjustment_order_4 = ''
        if stu.subjectname == '电子信息':
            research_direction = ''
            accept_adjustment = stu.accept_adjustment
            adjustment_order_1 = stu.adjustment_order_1
            adjustment_order_2 = stu.adjustment_order_2
            adjustment_order_3 = stu.adjustment_order_3
            adjustment_order_4 = stu.adjustment_order_4

        stu_info = {
            'name': stu.name,
            'stu_no': (stu.examnumber).exam_number_field,
            'gender': stu.gender,
            'major': stu.subjectname,
            'graduation_school': stu.undergradschool,
            'graduation_time': stu.graduationtime,
            'graduation_major': stu.undergradmajor,
            'stu_type': stu.stu_type,
            'category': stu.category,
            'contact_phone': stu.phone,
            'emergency_contact_phone': stu.emergencyphone,
            'preferred_mentor_1': stu.preferred_mentor_1,
            'preferred_mentor_2': stu.preferred_mentor_2,
            'preferred_mentor_3': stu.preferred_mentor_3,
            'research_direction': research_direction,
            'accept_adjustment': accept_adjustment,
            'adjustment_order_1': adjustment_order_1,
            'adjustment_order_2': adjustment_order_2,
            'adjustment_order_3': adjustment_order_3,
            'adjustment_order_4': adjustment_order_4,
        }
        stu.save()
        return render(request, '复试组复试信息表.html', {'student_info': stu_info})


# 返回学生主页
def stu_index(request):
    email = request.session.get('email')
    print(f"Email from session: {email}")
    student = models.student_table.objects.filter(email=email).first()
    stu = models.registration_table.objects.filter(examnumber=student.examnumber).first()
    if stu is not None:
        if stu.gender:
            if stu.gender == '1' or stu.gender == '男':
                stu.gender = '男'
            elif stu.gender == '2' or stu.gender == '女':
                stu.gender = '女'
            else:
                stu.gender = '未知'
        if stu.stu_type:
            if stu.stu_type == '1':
                stu.stu_type = '应届生'
            elif stu.stu_type == '2':
                stu.stu_type = '往届生'
            else:
                stu.stu_type = '同等学力'
        if stu.category:
            if stu.category == '1':
                stu.category = '定向生'
            else:
                stu.category = '非定向考生'
        if (stu.examnumber).exam_number_field:
            student_info = {'name': stu.name,
                            'stu_no': (stu.examnumber).exam_number_field,
                            'gender': stu.gender,
                            'major': stu.subjectname,
                            'graduation_school': stu.undergradschool,
                            'graduation_time': stu.graduationtime,
                            'graduation_major': stu.undergradmajor,
                            'stu_type': stu.stu_type,
                            'category': stu.category,
                            'contact_phone': stu.phone,
                            'emergency_contact_phone': stu.emergencyphone,
                            'preferred_mentor_1': stu.preferred_mentor_1,
                            'preferred_mentor_2': stu.preferred_mentor_2,
                            'preferred_mentor_3': stu.preferred_mentor_3,
                            'research_direction': stu.research_direction,
                            'accept_adjustment': stu.accept_adjustment,
                            'adjustment_order_1': stu.adjustment_order_1,
                            'adjustment_order_2': stu.adjustment_order_2,
                            'adjustment_order_3': stu.adjustment_order_3,
                            'adjustment_order_4': stu.adjustment_order_4,
                            'state': stu.state,
                            }
            return render(request, 'stu_index.html', {'student_info': student_info})
        if not email:
            return HttpResponse("Email is not set in session")
    else:
        return render(request, 'stu_index.html')


# 复试小组后台的搜索学生相关视图函数
def search_in_registration(request):
    student_infos = []
    if request.method == 'POST':
        student_name = request.POST.get('stu_name')
        if student_name:
            # 如果输入信息不为空
            print(student_name)
            stus = models.student_table.objects.filter(name=student_name)
            if stus.exists():  # 检查是否有匹配的学生
                for stu in stus:
                    # 获取学生的考试号
                    examnumber = stu.examnumber
                    stu_score = models.firstscore_table.objects.filter(examnumber=examnumber).first()  # 获取对应的分数记录
                    student_info = {
                        'examnumber': examnumber,
                        'name': stu.name,
                        'mathscore': stu_score.mathscore,
                        'englishscore': stu_score.englishscore,
                        'majorscore': stu_score.majorscore,
                        'politicalscore': stu_score.politicalscore,
                    }
                    student_infos.append(student_info)
                return render(request, '复试组后台.html', {'student_infos': student_infos})
            else:
                # 没有找到相关学生信息
                error_msg = "没有找到相关学生信息"
                return render(request, '复试组后台.html', {'error_msg': error_msg})
        else:
            error_msg = "请输入需要查找的学生姓名"
            return render(request, '复试组后台.html', {'error_msg': error_msg})
    return render(request, '复试组后台.html')


def get_stu_teacher_info(request):
    # 从导师主页的信息获取到导师的导师id
    if request.method == 'POST':
        teacher_id = request.POST.get('teacher_id')


# 定义返回学校主页的相关业务
def school_index(request):
    return render(request, 'index.html')


# 修改视图函数，区分是电子信息的学生还是计算机科学的学生，确定返回的数据，避免返回空数据在前端页面上
def stu_second_info(request):
    email = request.session.get('email')
    print(f"Email from session: {email}")  # 打印会话中的 email
    if email:
        # 获取到学生的相关信息
        student = models.student_table.objects.filter(email=email).first()
        student_second_info = models.registration_table.objects.filter(name=student.name).first()
        print(type(student))
        stu_info = {
            'name': student.name,
            'examnumber': (student.examnumber).exam_number_field,
            'gender': student_second_info.gender,
            'major': student_second_info.subjectname,
            'greduate_school': student_second_info.undergradschool,
            'graduate_time': student_second_info.graduationtime,
            'graduate_major': student_second_info.undergradmajor,
            'stu_type1': student_second_info.stu_type,
            'stu_type2': student_second_info.category,
            'phone_number': student_second_info.phone,
            'emergencyphone': student_second_info.emergencyphone,
            'teacher1': student_second_info.preferred_mentor_1,
            'teacher2': student_second_info.preferred_mentor_2,
            'teacher3': student_second_info.preferred_mentor_3,
            'research_direction': start_registration.research_direction,

        }
    return render(request, 'stu_index.html')


# 管理员用户界面信息

# 学科信息
def subject_info(request):
    subjects = models.subject_table.objects.all()  # 获取所有学科
    subjects_info = []
    for subject in subjects:
        subject_info = {
            'subject_id': subject.subjectid,
            'subject_name': subject.subjectname,
            'subject_level': subject.subjectlevel,
            'parent_subject': subject.parentsubject,
            'subject_overview': subject.subjectoverview,
            'subject_type': subject.subjecttype,
        }
        subjects_info.append(subject_info)  # 将信息添加到列表中
    return JsonResponse({'subjects_info': subjects_info})


@csrf_exempt
def add_subject(request):
    if request.method == "POST":
        data = json.loads(request.body)
        new_subject = models.subject_table(
            subjectid=data['subject_id'],
            subjectname=data['subject_name'],
            subjectlevel=data['subject_level'],
            parentsubject=data['parent_subject'],
            subjectoverview=data['subject_overview'],
            subjecttype=data['subject_type']
        )
        try:
            new_subject.save()
            return JsonResponse({'message': '科目已添加'}, status=201)
        except Exception as e:
            print(f"Error: {e}")
            return JsonResponse({'error': str(e)}, status=400)

@csrf_exempt
def delete_subject(request, subject_id):
    print(subject_id)
    try:
        subject = models.subject_table.objects.get(subjectid=subject_id)
        subject.delete()
        return JsonResponse({'message': '科目已删除'}, status=204)
    except models.subject_table.DoesNotExist:
        return JsonResponse({'message': '科目未找到'}, status=404)

@csrf_exempt
def get_subject(request, subject_id):
    try:
        subject = models.subject_table.objects.get(subjectid=subject_id)
        subject_info = {
            'subject_id': subject.subjectid,
            'subject_name': subject.subjectname,
            'subject_level': subject.subjectlevel,
            'parent_subject': subject.parentsubject,
            'subject_overview': subject.subjectoverview,
            'subject_type': subject.subjecttype,
        }
        return JsonResponse(subject_info, status=200)
    except models.subject_table.DoesNotExist:
        return JsonResponse({'message': '科目未找到'}, status=404)

@csrf_exempt
def edit_subject(request, subject_id):
    # 在视图中添加调试信息
    print(f"Attempting to edit subject with ID: {subject_id}")
    if request.method == "POST":
        try:
            data = json.loads(request.body)
            subject = models.subject_table.objects.get(subjectid=subject_id)
            subject.subjectname = data['subject_name']
            subject.subjectlevel = data['subject_level']
            subject.parentsubject = data['parent_subject']
            subject.subjectoverview = data['subject_overview']
            subject.subjecttype = data['subject_type']
            subject.save()
            return JsonResponse({'message': '科目更新成功', 'subject_id': subject_id}, status=200)  # 返回的subject_id
        except models.subject_table.DoesNotExist:
            return JsonResponse({'message': '科目未找到'}, status=404)
        except json.JSONDecodeError:
            return JsonResponse({'message': '无效的JSON格式'}, status=400)
    else:
        return JsonResponse({'message': '不支持的方法'}, status=405)

# 学生信息
def student_info(request):
    students = models.student_table.objects.all()  # 获取所有学生
    students_info = []
    for student in students:
        student_info = {
            'idnumber': student.idnumber,
            'name': student.name,
            'examnumber': student.examnumber,
            'origin': student.origin,
            'undergradmajor': student.undergradmajor,
            'undergradschool': student.undergradschool,
            'email': student.email,
            'phone': student.phone,
        }
        students_info.append(student_info)  # 将信息添加到列表中
    return JsonResponse({'students_info': students_info})
@csrf_exempt
def add_student(request):
    if request.method == "POST":
        data = json.loads(request.body)
        new_student = models.student_table(
            idnumber=data['idnumber'],
            name=data['name'],
            examnumber=data['examnumber'],
            origin=data['origin'],
            undergradmajor=data['undergradmajor'],
            undergradschool=data['undergradschool'],
            email=data['email'],
            phone=data['phone']
        )
        try:
            new_student.save()
            return JsonResponse({'message': '学生已添加'}, status=201)
        except Exception as e:
            print(f"Error: {e}")
            return JsonResponse({'error': str(e)}, status=400)

@csrf_exempt
def delete_student(request, idnumber):
    try:
        student = models.student_table.objects.get(idnumber=idnumber)
        student.delete()
        return JsonResponse({'message': '学生已删除'}, status=204)
    except models.student_table.DoesNotExist:
        return JsonResponse({'message': '学生未找到'}, status=404)

@csrf_exempt
def get_student(request, idnumber):
    try:
        student = models.student_table.objects.get(idnumber=idnumber)
        student_info = {
            'idnumber': student.idnumber,
            'name': student.name,
            'examnumber': student.examnumber,
            'origin': student.origin,
            'undergradmajor': student.undergradmajor,
            'undergradschool': student.undergradschool,
            'email': student.email,
            'phone': student.phone,
        }
        return JsonResponse(student_info, status=200)
    except models.student_table.DoesNotExist:
        return JsonResponse({'message': '学生未找到'}, status=404)

@csrf_exempt
def edit_student(request, idnumber):
    if request.method == "POST":
        try:
            data = json.loads(request.body)
            student = models.student_table.objects.get(idnumber=idnumber)
            student.name = data['name']
            student.examnumber = data['examnumber']
            student.origin = data['origin']
            student.undergradmajor = data['undergradmajor']
            student.undergradschool = data['undergradschool']
            student.email = data['email']
            student.phone = data['phone']
            student.save()
            return JsonResponse({'message': '学生更新成功', 'idnumber': idnumber}, status=200)
        except models.student_table.DoesNotExist:
            return JsonResponse({'message': '学生未找到'}, status=404)
        except json.JSONDecodeError:
            return JsonResponse({'message': '无效的JSON格式'}, status=400)
    else:
        return JsonResponse({'message': '不支持的方法'}, status=405)

# 导师信息
def teacher_info(request):
    teachers = models.teacher_table.objects.all()  # 获取所有导师
    teachers_info = []
    for teacher in teachers:
        teacher_info = {
            'instructorid': teacher.instructorid,
            'instructorname': teacher.instructorname,
            'instructorbio': teacher.instructorbio,
            'instructoremail': teacher.instructoremail,
            'instructorphone': teacher.instructorphone,
            'instructorsubject': teacher.instructorsubject,
            'instructortype': teacher.instructortype,
            'instructortitle': teacher.instructortitle,
        }
        teachers_info.append(teacher_info)  # 将信息添加到列表中
    return JsonResponse({'teachers_info': teachers_info})

@csrf_exempt
def add_teacher(request):
    if request.method == "POST":
        data = json.loads(request.body)
        new_teacher = models.teacher_table(
            instructorid=data['instructorid'],
            instructorname=data['instructorname'],
            instructorbio=data['instructorbio'],
            instructoremail=data['instructoremail'],
            instructorphone=data['instructorphone'],
            instructorsubject=data['instructorsubject'],
            instructortype=data['instructortype'],
            instructortitle=data['instructortitle'],
        )
        try:
            new_teacher.save()
            return JsonResponse({'message': '导师已添加'}, status=201)
        except Exception as e:
            return JsonResponse({'error': str(e)}, status=400)

@csrf_exempt
def delete_teacher(request, instructorid):
    try:
        teacher = models.teacher_table.objects.get(instructorid=instructorid)
        teacher.delete()
        return JsonResponse({'message': '导师已删除'}, status=204)
    except models.teacher_table.DoesNotExist:
        return JsonResponse({'message': '导师未找到'}, status=404)
@csrf_exempt
def get_teacher(request, instructorid):
    try:
        teacher = models.teacher_table.objects.get(instructorid=instructorid)
        teacher_info = {
            'instructorid': teacher.instructorid,
            'instructorname': teacher.instructorname,
            'instructorbio': teacher.instructorbio,
            'instructoremail': teacher.instructoremail,
            'instructorphone': teacher.instructorphone,
            'instructorsubject': teacher.instructorsubject,
            'instructortype': teacher.instructortype,
            'instructortitle': teacher.instructortitle,
        }
        return JsonResponse(teacher_info, status=200)
    except models.teacher_table.DoesNotExist:
        return JsonResponse({'message': '导师未找到'}, status=404)
@csrf_exempt
def edit_teacher(request, instructorid):
    if request.method == "POST":
        try:
            data = json.loads(request.body)
            teacher = models.teacher_table.objects.get(instructorid=instructorid)
            teacher.instructorname = data['instructorname']
            teacher.instructorbio = data['instructorbio']
            teacher.instructoremail = data['instructoremail']
            teacher.instructorphone = data['instructorphone']
            teacher.instructorsubject = data['instructorsubject']
            teacher.instructortype = data['instructortype']
            teacher.instructortitle = data['instructortitle']
            teacher.save()
            return JsonResponse({'message': '导师更新成功', 'instructorid': instructorid}, status=200)
        except models.teacher_table.DoesNotExist:
            return JsonResponse({'message': '导师未找到'}, status=404)
        except json.JSONDecodeError:
            return JsonResponse({'message': '无效的JSON格式'}, status=400)
    else:
        return JsonResponse({'message': '不支持的方法'}, status=405)

# 考生初试信息
def firstscore_info(request):
    students = models.firstscore_table.objects.all()
    firstscores_info = []
    for stu in students:
        # 假设 examnumber 是一个外键，那么应该使用 examnumber_id 来获取关联对象的ID
        stu_examnumber_id = stu.examnumber_id  # 获取关联学生表的ID
        stu_byid = models.student_table.objects.filter(examnumber=stu_examnumber_id).first()
        if stu_byid:
            student_info = {
                'examnumber': stu_examnumber_id,
                'name': stu_byid.name,
                'mathscore': stu.mathscore,
                'englishscore': stu.englishscore,
                'majorscore': stu.majorscore,
                'politicalscore': stu.politicalscore,
            }
            firstscores_info.append(student_info)
    return JsonResponse({'firstscores_info': firstscores_info})

@csrf_exempt
def add_firstscore(request):
    if request.method == "POST":
        data = json.loads(request.body)
        examnumber_instance, created_instructor = models.ExamNumber.objects.get_or_create(
            exam_number_field=data['examnumber'])

        print(data)
        new_firstscore = models.firstscore_table(
            examnumber=examnumber_instance,
            englishscore=data['englishscore'],
            mathscore=data['mathscore'],
            majorscore=data['majorscore'],
            politicalscore=data['politicalscore'],
        )
        try:
            new_firstscore.save()
            return JsonResponse({'message': '考生初试信息成功添加'}, status=200)
        except Exception as e:
            return JsonResponse({'error': str(e)}, status=400)


@csrf_exempt
def delete_firstscore(request, examnumber):
    try:
        # 先查找对应的初试成绩记录
        examnumber_instance, created_instructor = models.ExamNumber.objects.get_or_create(
            exam_number_field=examnumber)
        score = models.firstscore_table.objects.get(examnumber=examnumber_instance)
        score.delete()
        return JsonResponse({'message': '初试成绩已删除'}, status=204)
    except models.firstscore_table.DoesNotExist:
        return JsonResponse({'message': '初试成绩未找到'}, status=404)

@csrf_exempt
def edit_firstscore(request):
    if request.method == "POST":
        try:
            data = json.loads(request.body)
            examnumber = data.get('examnumber')  # 从请求体中获取 examnumber
            if not examnumber:
                return JsonResponse({'message': 'examnumber 是必需的'}, status=400)

            # 查找对应的初试成绩记录
            score = models.firstscore_table.objects.get(examnumber=examnumber)
            score.mathscore = data.get('mathscore', score.mathscore)
            score.englishscore = data.get('englishscore', score.englishscore)
            score.majorscore = data.get('majorscore', score.majorscore)
            score.politicalscore = data.get('politicalscore', score.politicalscore)
            score.save()

            return JsonResponse({'message': '初试成绩更新成功', 'examnumber': examnumber}, status=200)
        except models.firstscore_table.DoesNotExist:
            return JsonResponse({'message': '初试成绩未找到'}, status=404)
        except json.JSONDecodeError:
            return JsonResponse({'message': '无效的JSON格式'}, status=400)

    return JsonResponse({'message': '仅支持 POST 请求'}, status=405)


# 考生复试信息
def secondscore_info(request):
    students = models.secondscore_table.objects.all()
    secondscores_info = []
    for stu in students:
        # 假设 examnumber 是一个外键，那么应该使用 examnumber_id 来获取关联对象的ID
        stu_examnumber_id = stu.examnumber_id  # 获取关联学生表的ID
        stu_byid = models.student_table.objects.filter(examnumber=stu_examnumber_id).first()
        if stu_byid:
            student_info = {
                'examnumber': stu_examnumber_id,
                'name': stu_byid.name,
                'englishskills': stu.englishskills,
                'majorknowledge': stu.majorknowledge,
                'overallquality': stu.overallquality,
            }
            secondscores_info.append(student_info)
    return JsonResponse({'secondscores_info': secondscores_info})
@csrf_exempt
def secondscore_info(request):
    scores = models.secondscore_table.objects.all()
    secondscores_info = []
    for score in scores:
        student = models.student_table.objects.filter(examnumber=score.examnumber_id).first()
        if student:
            score_info = {
                'examnumber': score.examnumber_id,
                'name': student.name,
                'englishskills': score.englishskills,
                'majorknowledge': score.majorknowledge,
                'overallquality': score.overallquality,
            }
            secondscores_info.append(score_info)
    return JsonResponse({'secondscores_info': secondscores_info})



@csrf_exempt
def add_secondscore(request):
    if request.method == "POST":
        data = json.loads(request.body)
        # 先查找或创建ExamNumber实例
        exam_number_instance, created = models.ExamNumber.objects.get_or_create(
            exam_number_field=data['examnumber']
        )
        new_score = models.secondscore_table(
            examnumber=exam_number_instance,
            englishskills=data['englishskills'],
            majorknowledge=data['majorknowledge'],
            overallquality=data['overallquality']
        )
        try:
            new_score.save()
            return JsonResponse({'message': '复试成绩已添加'}, status=201)
        except Exception as e:
            return JsonResponse({'error': str(e)}, status=400)

@csrf_exempt
def delete_secondscore(request, examnumber):
    try:
        # 先查找对应的复试成绩记录
        examnumber_instance, created_instructor = models.ExamNumber.objects.get_or_create(
            exam_number_field=examnumber)
        score = models.secondscore_table.objects.get(examnumber=examnumber_instance)
        score.delete()
        return JsonResponse({'message': '复试成绩已删除'}, status=204)
    except models.secondscore_table.DoesNotExist:
        return JsonResponse({'message': '复试成绩未找到'}, status=404)
@csrf_exempt
def edit_secondscore(request):
    if request.method == "POST":

        try:
            data = json.loads(request.body)
            examnumber = data.get('examnumber')
            if not examnumber:
                return JsonResponse({'message': 'examnumber 是必需的'}, status=400)

            # 先查找对应的复试成绩记录
            score = models.secondscore_table.objects.get(examnumber=examnumber)
            score.englishskills = data['englishskills']
            score.majorknowledge = data['majorknowledge']
            score.overallquality = data['overallquality']
            score.save()
            return JsonResponse({'message': '复试成绩更新成功', 'examnumber': examnumber}, status=200)
        except models.firstscore_table.DoesNotExist:
            return JsonResponse({'message': '复试成绩未找到'}, status=404)
        except json.JSONDecodeError:
            return JsonResponse({'message': '无效的JSON格式'}, status=400)

    return JsonResponse({'message': '仅支持 POST 请求'}, status=405)

# 招生信息
def enrollment_info(request):
    enrollments_info = []
    enrollments = models.enrollment_table.objects.all()
    instructor_enrollments = enrollments.values(
        'instructorid__teacher_id_field',  # Assuming this is a foreign key field
        'subjectid__subject_id_field',  # Assuming this is a foreign key field
        'subjectdirection',
        'instructorname',
        'subjectexam',
        'subjectretest',
        'annualquota',
        'extraquota',
        'year',
        'eligible'
    ).annotate(instructor_id=F('instructorid__teacher_id_field'))

    for enrollment in instructor_enrollments:
        enrollment_info = {
            'subjectid': enrollment['subjectid__subject_id_field'],
            'subjectdirection': enrollment['subjectdirection'],
            'instructorname': enrollment['instructorname'],
            'subjectexam': enrollment['subjectexam'],
            'subjectretest': enrollment['subjectretest'],
            'annualquota': enrollment['annualquota'],
            'extraquota': enrollment['extraquota'],
            'year': enrollment['year'],
            'eligible': enrollment['eligible'],
            'instructorid': enrollment['instructor_id'],
        }
        enrollments_info.append(enrollment_info)

    return JsonResponse({'enrollments_info': enrollments_info})


@csrf_exempt  # 生产环境中请移除或使用更安全的CSRF保护方法
def add_enrollment(request):
    if request.method == "POST":
        print("Received request method:", request.method)
        print("Received request path:", request.path)
        try:
            data = json.loads(request.body)
            print(data['subjectid'])  # 打印请求的数据

            # 获取对应的导师和学科实例
            instructor_instance, created_instructor = models.TeacherId.objects.get_or_create(
                teacher_id_field=data['instructorid'])
            subject_instance, created_subject = models.SubjectId.objects.get_or_create(
                subject_id_field=data['subjectid'])
            # subject.save()
            # 创建新的招生信息
            new_enrollment = models.enrollment_table(
                instructorid=instructor_instance,
                subjectid=subject_instance,
                subjectdirection=data['subjectdirection'],
                subjectexam=data['subjectexam'],
                subjectretest=data['subjectretest'],
                annualquota=data['annualquota'],
                extraquota=data['extraquota'],
                year=data['year'],
                eligible=data['eligible']
            )
            print("招生信息已成功保存")  # 添加调试信息
            new_enrollment.save()  # 保存到数据库


            return JsonResponse({'message': '招生信息已添加'}, status=201)
        except models.TeacherId.DoesNotExist:
            return JsonResponse({'message': '导师未找到'}, status=404)
        except models.SubjectId.DoesNotExist:
            return JsonResponse({'message': '学科未找到'}, status=404)
        except Exception as e:
            print(f"发生错误: {e}")
            return JsonResponse({'message': '发生错误', 'error': str(e)}, status=500)

    return JsonResponse({'message': '不支持的方法'}, status=405)
@csrf_exempt
def delete_enrollment(request, instructorid):
    try:
        enrollment = models.enrollment_table.objects.get(instructorid=instructorid)
        enrollment.delete()
        return JsonResponse({'message': '招生信息已删除'}, status=204)
    except models.enrollment_table.DoesNotExist:
        return JsonResponse({'message': '招生信息未找到'}, status=404)



@csrf_exempt
def edit_enrollment(request, instructorid):
    if request.method == "POST":
        try:
            data = json.loads(request.body)
            instructor_instance, created_instructor = models.TeacherId.objects.get_or_create(
                teacher_id_field=data['instructorid'])
            subject_instance, created_subject = models.SubjectId.objects.get_or_create(
                subject_id_field=data['subjectid'])
            # 查找已存在的 enrollment 记录
            enrollment = models.enrollment_table.objects.get(instructorid=instructor_instance)
            # 更新 enrollment 对象的属性
            enrollment.instructorid = instructor_instance  # 为 instructorid 赋值
            enrollment.subjectid = subject_instance
            enrollment.subjectdirection = data['subjectdirection']
            enrollment.subjectexam = data['subjectexam']
            enrollment.subjectretest = data['subjectretest']
            enrollment.annualquota = data['annualquota']
            enrollment.extraquota = data['extraquota']
            enrollment.year = data['year']
            enrollment.eligible = data['eligible']  # 这里应该是布尔值，注意前端传值
            enrollment.save()
            return JsonResponse({'message': '招生信息已更新'}, status=200)

        except (models.enrollment_table.DoesNotExist, json.JSONDecodeError, KeyError) as e:
            return JsonResponse({'error': str(e)}, status=400)

    else:
        return JsonResponse({'message': '不支持的方法'}, status=405)


#师生交换信息表
def stutea_info(request):
    stuteas_info = []
    stuteas = models.student_teacher.objects.all()
    instructor_stuteas = stuteas.values(
        'instructorid__teacher_id_field',
        'examnumber__exam_number_field',
        'current_wish',
        'status',
    ).annotate(instructor_id=F('instructorid__teacher_id_field'))

    for stutea in instructor_stuteas:
        stutea_info = {
            'examnumber': stutea['examnumber__exam_number_field'],
            'status': stutea['status'],
            'current_wish': stutea['current_wish'],
            'instructorid': stutea['instructor_id'],
        }
        stuteas_info.append(stutea_info)

    return JsonResponse({'stuteas_info': stuteas_info})

#审核导师招生资格
def check_teacher(request):
    
    teachers = models.teacher_all_table.objects.all()  # 获取所有待审核的导师
    teachers_info = []
    for teacher in teachers:
        teacher_info = {
            'instructorid': teacher.instructorid,
            'instructorname': teacher.instructorname,
            'instructorbio': teacher.instructorbio,
            'instructoremail': teacher.instructoremail,
            'instructorphone': teacher.instructorphone,
            'instructorsubject': teacher.instructorsubject,
            'instructortype': teacher.instructortype,
            'instructortitle': teacher.instructortitle,
        }
        
        teachers_info.append(teacher_info)  # 将信息添加到列表中
    return JsonResponse({'teachers_info': teachers_info})


def admin(request):
    return render(request, 'Graduate_Administrator.html')


# 研究生主管领导管理页面
def Graduate_supervisor_leadership(request):
    return render(request, 'Graduate_supervisor_leadership.html')


# 研究生主管秘书管理页面
def Graduate_supervisor_Secretary(request):
    return render(request, 'Graduate_supervisor_Secretary.html')


# 学科负责人管理页面
def Head_of_Discipline(request):
    return render(request, 'Head_of_Discipline.html')


# 学科秘书管理页面
def Subject_Secretary(request):
    return render(request, 'Subject_Secretary.html')


# 将复试组提交的复试信息提交上传到数据库
def registory_info(request):
    if request.method == 'POST':
        place = request.POST.get('place')
        review = request.POST.get('review')
        leadersignature = request.POST.get('leadersignature')
        foreignlanguage = request.POST.get('foreignlanguage')
        knowledgetest = request.POST.get('knowledgetest')
        interview = request.POST.get('interview')
        totalscore = request.POST.get('totalscore')
        membersignature = request.POST.get('membersignature')
        mentorsignature = request.POST.get('mentorsignature')
        stu_no = request.POST.get('stu_id')
        # print(stu_no)
        stu = models.registration_table.objects.get(examnumber=stu_no)
        stu.retesttimeplace = place
        stu.evaluation = review
        stu.leadersignature = leadersignature
        stu.foreignlanguage = foreignlanguage
        stu.knowledgetest = knowledgetest
        stu.interview = interview
        stu.totalscore = totalscore
        stu.membersignature = membersignature
        stu.mentorsignature = mentorsignature
        stu.state = '1'
        stu.save()
        sucess_info = "提交成功!"
        return redirect('registration_info')
    else:
        fail_info = "提交失败!"
    return render(request, '复试组复试信息表.html', {'msg': fail_info})


# 导师信息页面返回所有导师信息
def teacher_information(request):
    teachers = models.teacher_table.objects.all()
    teachers_info = []
    for teacher in teachers:
        image_base64 = base64.b64encode(teacher.instructorphoto).decode('utf-8')
        image_data = f'data:image/jpeg;base64,{image_base64}'
        teacher_info = {
            'teacher_id': teacher.instructorid,
            'teacher_name': teacher.instructorname,
            'teacher_photo': image_data,
            'teacher_bio': teacher.instructorbio,
            'teacher_email': teacher.instructoremail,
            'teacher_phone': teacher.instructorphone,
            'teacher_subject': teacher.instructorsubject,
            'teacher_type': teacher.instructortype,
            'teacher_title': teacher.instructortitle,
        }
        # print(teacher.instructorname)
        teachers_info.append(teacher_info)
    return render(request, 'teacher_Information.html', {'teachers_info': teachers_info})


# 学科信息页面返回所有学科信息
def subject_information(request):
    subjects = models.subject_table.objects.all()  # 获取所有学科
    subjects_info = []

    for subject in subjects:
        subject_info = {
            'subject_id': subject.subjectid,
            'subject_name': subject.subjectname,
            'subject_level': subject.subjectlevel,
            'parent_subject': subject.parentsubject,
            'subject_overview': subject.subjectoverview,
            'subject_type': subject.subjecttype,
        }
        subjects_info.append(subject_info)  # 将信息添加到列表中
    return render(request, 'subject_Information.html', {'subjects_info': subjects_info})


# 推免招生页面
def recommended_admission(request):
    return render(request, 'recommended_Enrollment.html')


# 硕士招生页面
def master_admission(request):
    return render(request, 'master_Admission.html')


# 博士招生页面


def check_result(request):
    return render(request, 'check_result.html')


def search_result(request):
    if request.method == 'POST':
        student_info = {}
        student_id = request.POST.get('student_id')

        print(f'查询的学生ID: {student_id}')
        try:
            # 尝试获取 ExamNumber 实例
            exam_number_id_instance, created = models.ExamNumber.objects.get_or_create(
                exam_number_field=student_id
            )
            print(f'ExamNumber实例: {exam_number_id_instance}')

            # 尝试获取学生信息
            student = models.student_teacher.objects.filter(examnumber=exam_number_id_instance).first()
            if student is None:
                print('未找到学生记录')
                return JsonResponse({'error': '未找到学生记录'}, status=404)

            print(f'找到学生记录: {student}')

            # 使用 exam_number_field 的值来查找 student_table
            exam_number_value = exam_number_id_instance.exam_number_field
            print(f"正在尝试查找 student_table 中的记录，examnumber: {exam_number_value}")
            student_name = models.student_table.objects.filter(examnumber=exam_number_value).first()
            if student_name is None:
                print('未找到学生姓名')
                return JsonResponse({'error': '未找到学生信息'}, status=404)

            print(f'找到学生姓名: {student_name}')

            # 提取字段值而非对象
            student_info = {
                'id': str(exam_number_id_instance.exam_number_field),  # 提取学号
                'name': str(student_name.name),  # 提取学生姓名
                'state': '已录取' if str(student.status) == '1' else '未录取',  # 处理状态
            }

        except Exception as e:
            print(f'发生错误: {e}')
            return JsonResponse({'error': str(e)}, status=500)

        # 返回可序列化的 JSON 响应
        return JsonResponse({'msg': student_info})


def admin_dashboard(request):
    return HttpResponse()


def teacher_index(request):
    # 从会话中获取电子邮件
    email = request.session.get('email')

    # 获取与电子邮件匹配的第一个教师对象
    teacher = models.teacher_table.objects.filter(instructoremail=email).first()

    # 检查是否找到教师对象
    if teacher is not None:
        teacher_info = {
            'id': teacher.instructorid,  # 字典中需要使用冒号而不是等号
            'name': teacher.instructorname,
            'instructoremail': teacher.instructoremail,
            'instructorbio': teacher.instructorbio,
            'instructorphone': teacher.instructorphone,
            'instructorsubject': teacher.instructorsubject,
            'instructortype': teacher.instructortype,
            'instructortitle': teacher.instructortitle,
        }

        # print('debug_teacher_info:', teacher_info)  # 打印 teacher_info 字典
        return render(request, 'teacher_index.html', {'teacher_info': teacher_info})  # 将完整的 teacher_info 传递给模板
    else:
        # 处理未找到教师的情况
        print('老师未找到')
        return render(request, 'teacher_index.html', {'error': '未找到教师信息'})


from django.views.decorators.csrf import csrf_exempt



def tech_stu_info(request):
    if request.method == 'POST':
        teacher_id = request.POST.get('tech_no')
        print(f"Received teacher ID: {teacher_id}")
        if not teacher_id:
            return JsonResponse({'error': 'No teacher ID provided.'}, status=400)

        # 获取所有与导师相关的学生
        teacher_id_instance, created = models.TeacherId.objects.get_or_create(teacher_id_field=teacher_id)
        students = models.student_teacher.objects.filter(instructorid=teacher_id_instance)
        print(f"Students related to the teacher: {students}")

        # 提取学生的状态
        students_status = {}
        for student in students:
            print(student)
            exam_number_obj = student.examnumber
            exam_number = getattr(exam_number_obj, 'exam_number_field', None)
            if exam_number:
                students_status[exam_number] = student.status
        print(f"Students status mapping: {students_status}")

        # 从查询集中提取考号
        exam_numbers = students.values_list('examnumber__exam_number_field', flat=True)
        print(f"Exam numbers: {exam_numbers}")

        if not exam_numbers:
            return JsonResponse({'students': []})  # 没有找到学生

        # 查询成绩信息
        student_infos = []
        for exam_number in exam_numbers:
            ExamNumber_instance, created = models.ExamNumber.objects.get_or_create(exam_number_field=exam_number)
            first_scores = models.firstscore_table.objects.filter(examnumber=ExamNumber_instance)
            print(f"First scores for {exam_number}: {first_scores}")
            second_scores = models.secondscore_table.objects.filter(examnumber=ExamNumber_instance)
            print(f"Second scores for {exam_number}: {second_scores}")
            students_info = models.student_table.objects.filter(examnumber=exam_number)

            # 创建字典以便于查找
            first_score_dict = {fs.examnumber.exam_number_field: fs for fs in first_scores}
            print(f"First score dictionary: {first_score_dict}")
            second_score_dict = {ss.examnumber.exam_number_field: ss for ss in second_scores}
            print(f"Second score dictionary: {second_score_dict}")
            student_info_dict = {si.examnumber: si for si in students_info}

            # 填充学生信息
            stu_temp = first_score_dict.get(exam_number)
            stu_temp1 = second_score_dict.get(exam_number)
            stu_temp2 = student_info_dict.get(exam_number)

            # 确保学生状态能够找到
            student_status = students_status.get(exam_number, 'Unknown')
            print(f"Student status for {exam_number}: {student_status}")

            if stu_temp2:
                stu_info = {
                    'examnumber': exam_number,
                    'name': stu_temp2.name if stu_temp2 else None,
                    'englishscore': stu_temp.englishscore if stu_temp else None,
                    'mathscore': stu_temp.mathscore if stu_temp else None,
                    'majorscore': stu_temp.majorscore if stu_temp else None,
                    'politicalscore': stu_temp.politicalscore if stu_temp else None,
                    'englishskills': stu_temp1.englishskills if stu_temp1 else None,
                    'majorknowledge': stu_temp1.majorknowledge if stu_temp1 else None,
                    'overallquality': stu_temp1.overallquality if stu_temp1 else None,
                    'status': student_status,  # 添加状态字段
                }
                student_infos.append(stu_info)

        return JsonResponse({'students': student_infos}, safe=False)

    return JsonResponse({'error': 'Invalid request method.'}, status=405)



def test(request):
    if request.method == 'POST':
        exam_number_id = request.POST.get('exam_number')
        action = request.POST.get('action')
        print(action)
        if not exam_number_id:
            return JsonResponse({'message': '考号无效！'}, status=400)
        try:
            # 查询或更新 ExamNumber 实例
            exam_number_id_instance, created = models.ExamNumber.objects.update_or_create(
                exam_number_field=exam_number_id,
                defaults={'exam_number_field': exam_number_id}
            )
            if action == 'reject':
                # 查询学生信息
                student_info = models.student_teacher.objects.filter(examnumber_id=exam_number_id_instance).first()
                if not student_info and student_info.status == '0':
                    return JsonResponse({'message': f'未找到考号为 {exam_number_id} 的学生。'}, status=404)
                # 根据当前学生examnumber查询学生志愿对应的导师
                next_teacner = models.registration_table.objects.filter(examnumber=exam_number_id_instance).first()
                if student_info.current_wish == '1':
                    # 若当前学生的志愿是志愿一，那么就加载志愿二进入表中，并且修改当前学生志愿为志愿二
                    next_teacher_name = next_teacner.preferred_mentor_2
                    student_info.current_wish = '2'
                elif student_info.current_wish == '2':
                    # 如果当前志愿是学生的志愿二，那么就加载学生的志愿三进入表中，并且修改当前志愿为志愿三
                    next_teacher_name = next_teacner.preferred_mentor_3
                    student_info.current_wish = '3'
                # next_teacher_name = '西门子轩'
                print(next_teacher_name)
                # print('current_teacher:', student_info.instructorid)
                # 保存当前教师的 ID，以备后续删除原条目使用
                primeval_teacherid = student_info.instructorid
                # 从 teacher_table 查询教师记录
                try:
                    teacher_record = models.teacher_table.objects.get(instructorname=next_teacher_name)
                    print(teacher_record)
                    # 确保教师记录中的 ID 是有效的
                    if not teacher_record.instructorid:
                        return JsonResponse({'message': '无效的教师 ID。'}, status=400)
                    # 查找或创建 TeacherId 实例
                    teacher_id_instance, _ = models.TeacherId.objects.get_or_create(
                        teacher_id_field=teacher_record.instructorid
                    )
                    # 更新学生信息
                    student_info.instructorid = teacher_id_instance
                    student_info.examnumber = exam_number_id_instance
                    student_info.save()
                    # 删除原来的条目
                    if primeval_teacherid:
                        models.student_teacher.objects.filter(
                            examnumber_id=exam_number_id_instance,
                            instructorid=primeval_teacherid
                        ).delete()
                    message = f"学生 {exam_number_id} 已被 {action}。"  # 生成反馈消息
                except models.teacher_table.DoesNotExist:
                    message = f"未找到导师名称为", next_teacher_name, "的教师。"  # 如果没有找到教师
                except Exception as e:  # 捕捉其它可能的异常
                    message = f"发生错误：{str(e)}"
            elif (action == 'accept'):
                student_info = models.student_teacher.objects.filter(examnumber_id=exam_number_id_instance).first()
                print(student_info.status)
                # 将学生与导师之间绑定的状态设置为1
                student_info.status = 1
                print('修改之后的学生状态', student_info.status)
                student_info.save()
                print('写入成功')
                message = f"学生 {exam_number_id} 已被 {action}。"  # 生成反馈消息
            return JsonResponse({'message': message})
        except Exception as e:
            return JsonResponse({'message': f'发生错误：{str(e)}'}, status=500)
    return JsonResponse({'message': '无效请求！'}, status=400)

def input_teacher_info(request):
    if request.method == 'POST':
        teacher_id = request.POST.get('teacher_id')
        teacher_name = request.POST.get('teacher_name')
        teacher_bio = request.POST.get('teacher_bio')
        teacher_email = request.POST.get('teacher_email')
        teacher_phone = request.POST.get('teacher_phone')
        teacher_subject = request.POST.get('teacher_subject')
        if not teacher_id:
            return JsonResponse({'message': '无效的教师 ID。'}, status=400)
        try:
            # 查找或创建教师记录
            teacher_record, created = models.teacher_table.objects.get_or_create(
                instructorid=teacher_id,
                defaults={
                    'instructorname': teacher_name,
                    'instructorbio': teacher_bio,
                    'instructoremail': teacher_email,
                    'instructorphone': teacher_phone,
                    'instructorsubject': teacher_subject,
                }
            )
            if not created:
                teacher_record.instructorname = teacher_name
                teacher_record.instructorbio = teacher_bio
                teacher_record.instructoremail = teacher_email
                teacher_record.instructorphone = teacher_phone
                teacher_record.instructorsubject = teacher_subject
                teacher_record.save()
            return JsonResponse({'message': '教师信息已保存。'})
        except Exception as e:
            return JsonResponse({'message': f'发生错误：{str(e)}'}, status=500)
    return JsonResponse({'message': '无效请求！'}, status=400)

